package com.tonann.web.api;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tonann.app.domain.*;
import com.tonann.app.dto.AppDeviceModelDto;
import com.tonann.app.dto.FaultHandleDto;
import com.tonann.app.service.*;
import com.tonann.common.constant.CacheConstants;
import com.tonann.common.core.controller.BaseController;
import com.tonann.common.core.domain.AjaxResult;
import com.tonann.common.core.domain.entity.SysPlace;
import com.tonann.common.core.domain.entity.SysUser;
import com.tonann.common.utils.DateUtils;
import com.tonann.common.utils.StringUtils;
import com.tonann.common.utils.sign.Base64;
import com.tonann.system.service.ISysDictDataService;
import com.tonann.system.service.ISysPlaceService;
import com.tonann.system.service.ISysUserService;
import com.tonann.web.dangerous.DangerousToken;
import com.tonann.web.dangerous.OkHttpUtil;
import com.tonann.web.vo.AppFaultVO;
import com.tonann.web.vo.DeviceVO;
import com.tonann.weixin.config.WxMaProperties;
import com.tonann.weixin.domain.WxUser;
import com.tonann.weixin.entity.PhoneDto;
import com.tonann.weixin.model.WXAccessToken;
import com.tonann.weixin.model.WeChatPhoneInfo;
import com.tonann.weixin.service.IWxUserService;
import com.tonann.weixin.utils.ThirdSessionHolder;
import io.swagger.annotations.Api;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.spec.AlgorithmParameterSpec;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * APP端接口Controller
 *
 * @author ruoyi
 * @date 2022-04-06
 */
@Api("App端接口管理")
@RestController
@RequestMapping("/weixin/api")
public class AppInterfaceApi extends BaseController {
    @Autowired
    private WxMaProperties wxMaProperties;

    @Autowired
    private ISysPlaceService placeService;

    @Autowired
    private IAppDeviceService deviceService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IAppSensorService sensorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IAppFaultService faultService;

    @Autowired
    private IAppFaultHandleService faultHandleService;

    @Autowired
    private IAppFaultHandleRecordService faultHandleRecordService;

    @Autowired
    private IAppFaultReadService faultReadService;

    @Autowired
    private IAppFaultRuleService faultRuleService;

    @Autowired
    private IAppFeedBackService feedBackService;

    @Autowired
    private IAppOneKeyRepairService oneKeyRepairService;

    @Autowired
    private IAppFaultService appFaultService;

    @Autowired
    private IAppDeviceModelService appDeviceModelService;

    @Autowired
    private IAppDeviceDocumentService appDeviceDocumentService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    String sn = "9f68d9ed899c492dbacfd92a07f42756";
    String model_id = "Hwhlj4ySIMTAaK-LW8BPNA";

    /**
     * 解密并且获取用户手机号码
     *
     * @param encrypdata
     * @param ivdata
     * @param sessionkey
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deciphering", method = RequestMethod.GET)
    public @ResponseBody
    PhoneDto deciphering(String encrypdata,
                         String ivdata, String sessionkey,
                         HttpServletRequest request) {

        byte[] encrypData = Base64.decode(encrypdata);
        byte[] ivData = Base64.decode(ivdata);
        byte[] sessionKey = Base64.decode(sessionkey);
        String str = "";
        try {
            str = decrypt(sessionKey, ivData, encrypData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(str);
        PhoneDto phoneDto = new PhoneDto();
        phoneDto.setPhone(str);
        phoneDto.setModelId(this.model_id);
        phoneDto.setSn(this.sn);
        JSONObject jsonObject = this.getSnTicket();
        String snTicket = jsonObject.get("sn_ticket", String.class);
        phoneDto.setSnTicket(snTicket);
        return phoneDto;

    }

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串
        return new String(cipher.doFinal(encData), "UTF-8");
    }

    @GetMapping(value = "/phonenumber")
    public AjaxResult getPhoneNumber(String appId, String code) {
        Long startTime = WXAccessToken.getInstance().getGetTime();
        if (startTime == null || System.currentTimeMillis() / 1000 - startTime > 0) {
            JSONObject jsonObject = this.getToken(appId);
            Integer expiresTime = jsonObject.get("expires_in", Integer.class);
            String accessToken = jsonObject.get("access_token", String.class);
            WXAccessToken.getInstance().setWxAccessToken(accessToken);
            WXAccessToken.getInstance().setGetTime(System.currentTimeMillis() / 1000 + expiresTime);
        }
        String accessToken = WXAccessToken.getInstance().getAccessToken();
        JSONObject phoneNumberJson = this.getPhone(accessToken, code);
        if (phoneNumberJson.get("errcode", Integer.class) == 40001) {
            JSONObject json = this.getToken(appId);
            accessToken = json.get("access_token", String.class);
            phoneNumberJson = this.getPhone(accessToken, code);
            System.out.println("errcode:" + phoneNumberJson.get("errcode", Integer.class));
        }
        WeChatPhoneInfo phoneInfo = phoneNumberJson.get("phone_info", WeChatPhoneInfo.class);
        if (phoneInfo == null) {
            return null;
        }
        PhoneDto phoneDto = new PhoneDto();
        phoneDto.setPhone(phoneInfo.getPurePhoneNumber());
        phoneDto.setModelId(this.model_id);
        phoneDto.setSn(this.sn);
        JSONObject jsonObject = this.getSnTicket();
        String snTicket = jsonObject.get("sn_ticket", String.class);
        phoneDto.setSnTicket(snTicket);
        return AjaxResult.success(phoneDto);
    }

    public JSONObject getPhone(String accessToken, String code) {
        String result = null;
        // 接口调用凭证：accessToken
        String baseUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        HashMap<String, Object> requestParam = new HashMap<>();
        // 手机号调用凭证
        requestParam.put("code", code);
        // 发送post请求读取调用微信接口获取openid用户唯一标识
        String jsonStr = JSONUtil.toJsonStr(requestParam);
        HttpResponse response = HttpRequest.post(baseUrl)
                .header(Header.CONTENT_ENCODING, "UTF-8")
                // 发送json数据需要设置contentType
//                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .header(Header.CONTENT_TYPE, "application/json")
                .body(jsonStr)
                .execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {
            result = response.body();
        }
        System.out.println(result);
        return JSONUtil.parseObj(result);
    }

    public JSONObject getToken(String appId) {
        String result = null;
        String APPSECRET = null;
        List<WxMaProperties.Config> configs = wxMaProperties.getConfigs();
        if (configs != null) {
            for (WxMaProperties.Config config : configs) {
                String app = config.getAppId();
                if (app.equals(appId)) {
                    APPSECRET = config.getSecret();
                }
            }
        }
        if (APPSECRET == null) {
            return null;
        }
        // 接口调用凭证：accessToken
        String baseUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + APPSECRET;
        HttpResponse response = HttpRequest.get(baseUrl)
                .header(Header.CONTENT_ENCODING, "UTF-8")
                // 发送json数据需要设置contentType
                .header(Header.CONTENT_TYPE, "application/json")
                .execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {
            result = response.body();
        }
        return JSONUtil.parseObj(result);
    }

    public JSONObject getSnTicket() {
        String ACCESS_TOKEN = null;
        // 微信小程序ID
        String appid = "wx6e420f8197aa9b3d";
        Long startTime = WXAccessToken.getInstance().getGetTime();
        if (startTime == null || System.currentTimeMillis() / 1000 - startTime > 0) {
            JSONObject jsonObject = this.getToken(appid);
            Integer expiresTime = jsonObject.get("expires_in", Integer.class);
            String accessToken = jsonObject.get("access_token", String.class);
            WXAccessToken.getInstance().setWxAccessToken(accessToken);
            WXAccessToken.getInstance().setGetTime(System.currentTimeMillis() / 1000 + expiresTime);
        }
        ACCESS_TOKEN = WXAccessToken.getInstance().getAccessToken();
        String result = null;
        // 接口调用凭证：accessToken
        String baseUrl = "https://api.weixin.qq.com/wxa/getsnticket?access_token=" + ACCESS_TOKEN;
        HashMap<String, Object> requestParam = new HashMap<>();
        // 手机号调用凭证
        requestParam.put("sn", sn);
        requestParam.put("model_id", model_id);
        // 发送post请求读取调用微信接口获取openid用户唯一标识
        String jsonStr = JSONUtil.toJsonStr(requestParam);
        HttpResponse response = HttpRequest.post(baseUrl)
                .header(Header.CONTENT_ENCODING, "UTF-8")
                // 发送json数据需要设置contentType
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(jsonStr)
                .execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {
            result = response.body();
        }
        return JSONUtil.parseObj(result);
    }

    @GetMapping("/getDevice")
    public AjaxResult getDeviceById(String deviceId) throws Exception {
        if (deviceId != null) {
            Long id = Long.parseLong(deviceId);
            AppDevice appDevice = deviceService.selectAppDeviceByDeviceId(id);
            List<AppDevice> appDeviceList = deviceService.selectChildrenAppDeviceById(id);
            appDevice.setChildren(appDeviceList);
            DeviceVO vo = getVO(appDevice);
            getList(vo, appDevice);
            if (vo.getType().equals("1")) {
                List<DeviceVO> voList = vo.getChildrenVO();
                List<AppSensor> list = vo.getSensorList();
                for (DeviceVO deviceVO : voList) {
                    list.addAll(deviceVO.getSensorList());
                }
                vo.setSensorList(list);
            }
            return AjaxResult.success(vo);
        }
        return AjaxResult.error();
    }

    private void getList(DeviceVO vo, AppDevice appDevice) throws Exception {
        List<AppDevice> appDeviceList = deviceService.selectChildrenAppDeviceById(appDevice.getDeviceId());
        if (appDeviceList != null && appDeviceList.size() > 0) {
            List<DeviceVO> voList = new ArrayList<>();
            for (AppDevice device : appDeviceList) {
                DeviceVO v = getVO(device);
                voList.add(v);
                getList(v, device);
            }
            vo.setChildrenVO(voList);
        }
    }

    private DeviceVO getVO(AppDevice appDevice) throws Exception {
        DeviceVO vo = new DeviceVO();
        BeanUtils.copyProperties(vo, appDevice);
        List<Long> placeIds = deviceService.selectAppDevicePlaceListByDeviceId(appDevice.getDeviceId());
        String placeName = "";
        for (Long placeId : placeIds) {
            SysPlace place = placeService.selectPlaceById(placeId);
            if (place != null) {
                placeName += place.getPlaceName();
            }
        }
        List<Long> userIds = deviceService.selectAdminPhoneByDeviceId(appDevice.getDeviceId());
        List<SysUser> phones = new ArrayList<>();
        for (Long userId : userIds) {
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (sysUser != null) {
                phones.add(sysUser);
            }
        }
        vo.setPosition(placeName);
        vo.setPhone(phones);
        List<AppFault> faultList = appFaultService.selectUnCheckedAppFaultListByDeviceId(appDevice.getDeviceId());
        String alarm = "";
        Map<Long, AppFault> faultMap = new HashedMap<>();
        for (AppFault appFault : faultList) {
            AppFault fault = faultMap.get(appFault.getFaultRuleId());
            if (fault == null) {
                faultMap.put(appFault.getFaultRuleId(), appFault);
            } else if (appFault.getCreateTime().compareTo(fault.getCreateTime()) > 0) {
                faultMap.put(appFault.getFaultRuleId(), appFault);
            }
        }
        List<String> alarmList = new ArrayList<>();
        for (Long key : faultMap.keySet()) {
            AppFault fault = faultMap.get(key);
            if (fault != null) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = simpleDateFormat.format(fault.getCreateTime());
                alarm += fault.getFaultName() + ":" + dateStr;
                alarm = vo.getDeviceName() + ":" + alarm;
                alarmList.add(alarm);
            }
        }
        vo.setAlarmContent(alarmList);
        AppSensor appSensor = new AppSensor();
        appSensor.setDeviceId(appDevice.getDeviceId());
        List<AppSensor> sensorList = sensorService.selectAppSensorAllListByDeviceId(appDevice.getDeviceId());
        List<AppSensor> powerStatusSensorList = new ArrayList<>();
        List<AppSensor> appSensorLis = new ArrayList<>();
        if (sensorList.size() > 0) {
            for (AppSensor sensor : sensorList) {
//                AppSensor s = mongoTemplate.findById(sensor.getSensorId(), AppSensor.class);
                String value = null;
                Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                if (object != null){
                    if (object instanceof  String){
                        value = object.toString();
                    }if (object instanceof BigDecimal){
                        value = object.toString();
                    }
                }
                if (value != null) {
                    if (sensor.getSensorType().equals("4")) {
                        vo.setAirVolume(value);
                    } else if (sensor.getSensorType().equals("9")) {
                        vo.setAirSpeed(value);
                    } else if (sensor.getUnit().equals("cm") && (sensor.getIsHeight() == null || sensor.getIsHeight().equals("0"))) {
                        vo.setWindowHeight(value);
                    } else if (sensor.getSensorType().equals("13")) {
                        vo.setAngle(value);
                    } else if (sensor.getSensorType().equals("2")) {
                        vo.setHumidity(value);
                    } else if (sensor.getSensorType().equals("1")) {
                        vo.setTemperature(value);
                    } else if (sensor.getSensorType().equals("3")) {
                        vo.setPressure(value);
                    } else if (sensor.getSensorType().equals("6")) {
                        vo.setPowerConsumption(value);
                    } else if (sensor.getSensorType().equals("10")) {
                        vo.setFrequency(value);
                    } else if (sensor.getSensorType().equals("11")) {
                        vo.setAmpere(value);
                    } else if (sensor.getSensorType().equals("16")) {
                        vo.setTvoc(value);
                    } else if (sensor.getSensorType().equals("21")) {
                        vo.setCH2O(value);
                    } else if (sensor.getSensorType().equals("23")) {
                        vo.setO2(value);
                    } else if (sensor.getSensorType().equals("15")) {
                        vo.setNoise(value);
                    } else if (sensor.getSensorType().equals("14")) {
                        vo.setIllumination(value);
                    } else if (sensor.getSensorType().equals("20")) {
                        vo.setCO2(value);
                    } else if (sensor.getSensorType().equals("19")) {
                        vo.setPM1(value);
                    } else if (sensor.getSensorType().equals("18")) {
                        vo.setPM10(value);
                    } else if (sensor.getSensorType().equals("17")) {
                        vo.setPM2Point5(value);
                    } else if (sensor.getSensorType().equals("25")) {
                        vo.setRawWaterConductivity(value);
                    } else if (sensor.getSensorType().equals("26")) {
                        vo.setFirstWaterConductivity(value);
                    } else if (sensor.getSensorType().equals("27")) {
                        vo.setSecondWaterConductivity(value);
                    } else if (sensor.getSensorType().equals("28")) {
                        vo.setLiquidLevel(value);
                    } else if (sensor.getUnit().equals("开关量")) {
                        if (value != null) {
                            if (StringUtils.endsWith(value, ".0")) {
                                String val = StringUtils.substringBefore(value, ".0");
//                                s.setValue(val);
                                redisTemplate.opsForValue().set(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId(), val.toString());
                            }
                        }
                        if (sensor.getIsLight() != null && sensor.getIsLight().equals("1")) {
                            vo.setLight(value);
                        } else if (sensor.getIsForce() != null && sensor.getIsForce().equals("1")) {
                            vo.setForce(value);
                        } else if (sensor.getIsOn() != null && sensor.getIsOn().equals("1")) {
                            vo.setPower(value);
                            sensor.setValue(value);
                            appSensorLis.add(sensor);
                        } else if (sensor.getIsAutoDoor() != null && sensor.getIsAutoDoor().equals("1")) {
                            vo.setIsAutoDoor(value);
                        } else if (sensor.getIsBeing() != null && sensor.getIsBeing().equals("1")) {
                            vo.setIsBeing(value);
                        } else if (sensor.getWorkMode() != null && sensor.getWorkMode().equals("1")) {
                            vo.setWorkingMode(value);
                        }
                    }
                    if (sensor.getSensorType().equals("24")) {
                        sensor.setValue(value);
                    }
                }
                if (sensor.getSensorType().equals("24")) {
                    powerStatusSensorList.add(sensor);
                }else if (sensor.getSensorType().equals("22") && sensor.getIsOn() != null && sensor.getIsOn().equals("1") && vo.getPower() == null) {
                    vo.setPower("0");
                    vo.setIsRunning("0");
                    vo.setIsOnline("0");
                    sensor.setValue("0");
                    appSensorLis.add(sensor);
                }
            }
        }
        if (powerStatusSensorList.size() > 0) {
            for (AppSensor sensor : powerStatusSensorList) {
                if (sensor.getValue() != null && !sensor.getValue().trim().equals("")) {
                    if (StringUtils.endsWith(sensor.getValue(), ".0")) {
                        String val = StringUtils.substringBefore(sensor.getValue(), ".0");
                        sensor.setValue(val);
                    }
                    vo.setPower(sensor.getValue());
                } else {
                    vo.setPower("0");
                }
            }
        }
        vo.setSensorList(appSensorLis);
        return vo;
    }

    @PostMapping("/updateDevice")
    public AjaxResult updateDeviceById(@RequestBody DeviceVO device) throws Exception {
        if (device != null && device.getDeviceId() != null) {
            AppSensor appSensor = new AppSensor();
            if (device.getCommandKey() != null) {
                switch (device.getCommandKey()) {
                    case "light":
                        appSensor.setIsLight("1");
                        break;
                    case "power":
                        appSensor.setIsOn("1");
                        break;
                    case "force":
                        appSensor.setIsForce("1");
                        break;
                    case "windowHeight":
                        appSensor.setIsHeight("1");
                        break;
                    case "mode":
                        appSensor.setWorkMode("1");
                        break;
                    case "isAutoDoor":
                        appSensor.setIsAutoDoor("1");
                        break;
                }
            }
            appSensor.setDeviceId(device.getDeviceId());
            List<AppSensor> sensorList = sensorService.selectAppSensorAllList(appSensor);
            if (sensorList != null && sensorList.size() > 0) {
                AppSensor sensor = sensorList.get(0);
                sensor.setValue(device.getCommandValue());
                sensorService.updateAppSensorStatus(sensor);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @PostMapping("/updateSensor")
    public AjaxResult updateSensor(@RequestBody List<AppSensor> sensorList) {
        if (sensorList != null && sensorList.size() > 0) {
            for (AppSensor sensor : sensorList) {
                sensorService.updateAppSensorStatus(sensor);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @GetMapping("/getAlarm")
    public AjaxResult getAlarm(String orderLevel, String orderTime) {
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.selectWxUserById(id);
        List<AppFault>[] vo = new List[2];
        if (wxUser.getPhone() != null) {
            List<SysUser> userList = sysUserService.selectUserByPhone(wxUser.getPhone());
            if (userList.size() > 0) {
                SysUser sysUser = userList.get(0);
                List<AppDevice> deviceList = deviceService.selectDeviceListByUserId(sysUser.getUserId());
                Set<Long> set = new HashSet<>();
                for (AppDevice device : deviceList) {
                    set.add(device.getDeviceId());
                }
                List<AppFault> readFaultList = faultService.selectAppFaultByDeviceIds(set, sysUser.getUserId(), "1", orderLevel, orderTime);
                List<AppFault> unreadFaultList = faultService.selectAppFaultByDeviceIds(set, sysUser.getUserId(), "0", orderLevel, orderTime);

                vo[0] = unreadFaultList;
                vo[1] = readFaultList;
            }
        }
        return AjaxResult.success(vo);
    }

    @GetMapping("/updateAlarmRead")
    public AjaxResult updateAlarmRead(Long faultId) {
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.selectWxUserById(id);
        if (wxUser.getPhone() != null) {
            List<SysUser> userList = sysUserService.selectUserByPhone(wxUser.getPhone());
            if (userList.size() > 0) {
                SysUser sysUser = userList.get(0);
                AppFaultRead faultRead = new AppFaultRead();
                faultRead.setFaultId(faultId);
                faultRead.setUserId(sysUser.getUserId());
                List<AppFaultRead> list = faultReadService.selectAppFaultReadList(faultRead);
                if (list == null || list.size() == 0) {
                    faultRead.setUpdateBy(sysUser.getUserName());
                    faultRead.setUpdateTime(new Date());
                    faultRead.setCreateBy(sysUser.getUserName());
                    faultRead.setCreateTime(new Date());
                    faultReadService.insertAppFaultRead(faultRead);
                }
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/getAlarmDetail")
    public AjaxResult getAlarmDetail(Long faultId) {
        AppFault fault = faultService.selectAppFaultByFaultId(faultId);
        AppFaultVO vo = new AppFaultVO();
        BeanUtil.copyProperties(fault, vo);
        if (vo.getDeviceId() != null) {
            AppDevice appDevice = deviceService.selectAppDeviceByDeviceId(vo.getDeviceId());
            vo.setAppDevice(appDevice);
        }
        if (vo.getSensorId() != null) {
            AppSensor appSensor = sensorService.selectAppSensorBySensorId(vo.getSensorId());
            vo.setAppSensor(appSensor);
        }
        if (vo.getFaultRuleId() != null) {
            AppFaultRule appFaultRule = faultRuleService.selectAppFaultRuleByFaultRuleId(vo.getFaultRuleId());
            vo.setAppFaultRule(appFaultRule);
        }
        AppFaultHandle faultHandle = faultHandleService.selectAppFaultHandleByFaultId(faultId);
        vo.setFaultHandle(faultHandle);
        if (faultHandle != null && faultHandle.getHandleId() != null) {
            AppFaultHandleRecord record = new AppFaultHandleRecord();
            record.setHandleId(faultHandle.getHandleId());
            List<AppFaultHandleRecord> faultHandleRecordList = faultHandleRecordService.selectAppFaultHandleRecordList(record);
            vo.setHandleRecordList(faultHandleRecordList);
        }
        return AjaxResult.success(vo);
    }

    @PostMapping("/dismissAlarm")
    public AjaxResult dismissAlarm(@RequestBody FaultHandleDto faultHandleDto) {
        AppFaultHandle faultHandle = faultHandleService.selectAppFaultHandleByFaultId(faultHandleDto.getFaultId());
        if (faultHandle == null) {
            faultHandle = new AppFaultHandle();
            faultHandle.setFaultId(faultHandleDto.getFaultId());
        }
        faultHandle.setHandleRecord(faultHandleDto.getRecord());
        faultHandle.setIsChecked(faultHandleDto.getIsDismiss());
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.selectWxUserById(id);
        if (wxUser.getPhone() != null) {
            List<SysUser> userList = sysUserService.selectUserByPhone(wxUser.getPhone());
            if (userList.size() > 0) {
                SysUser sysUser = userList.get(0);
                if (sysUser != null) {
                    faultHandle.setUserId(sysUser.getUserId());
                    if (faultHandle.getHandleId() == null) {
                        faultHandle.setCreateBy(sysUser.getUserName());
                        faultHandle.setCreateTime(DateUtils.getNowDate());
                    }
                    faultHandle.setUpdateTime(DateUtils.getNowDate());
                    faultHandle.setUpdateBy(sysUser.getUserName());
                }
            }
        }
        if (faultHandle.getHandleId() == null) {
            faultHandleService.insertAppFaultHandle(faultHandle);
        } else {
            faultHandleService.updateAppFaultHandle(faultHandle);
        }
        AppFaultHandleRecord faultHandleRecord = new AppFaultHandleRecord();
        faultHandleRecord.setHandleId(faultHandle.getHandleId());
        faultHandleRecord.setHandleRecord(faultHandleDto.getRecord());
        faultHandleRecord.setUpdateBy(faultHandle.getUpdateBy());
        faultHandleRecord.setCreateBy(faultHandle.getCreateBy());
        faultHandleRecord.setCreateTime(new Timestamp(new Date().getTime()));
        faultHandleRecord.setUpdateTime(new Timestamp(new Date().getTime()));
        faultHandleRecord.setUserId(faultHandle.getUserId());
        faultHandleRecordService.insertAppFaultHandleRecord(faultHandleRecord);
        return AjaxResult.success();
    }

    @PostMapping("/feedback")
    public AjaxResult addFeedback(@RequestBody AppFeedBack feedBack) {
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.selectWxUserById(id);
        if (wxUser != null) {
            feedBack.setOpenId(wxUser.getOpenId());
            feedBack.setNickName(wxUser.getNickName());
            feedBack.setIsCommon("0");
            feedBack.setCreateTime(new Timestamp(new Date().getTime()));
            feedBack.setUpdateTime(new Timestamp(new Date().getTime()));
            if (feedBack.getFeedImg() != null && StringUtils.endsWith(feedBack.getFeedImg(), ".0")) {
                String s = feedBack.getFeedImg();
                feedBack.setFeedImg(StringUtils.substringBefore(s, ".0"));
            }
            return AjaxResult.success(feedBackService.insertAppFeedBack(feedBack));
        }
        return AjaxResult.error();
    }

    @GetMapping("/myFeedback")
    public AjaxResult myFeedback() {
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.selectWxUserById(id);
        if (wxUser != null) {
            AppFeedBack feedBack = new AppFeedBack();
            feedBack.setOpenId(wxUser.getOpenId());
            List<AppFeedBack> list = feedBackService.selectAppFeedBackList(feedBack);
            return AjaxResult.success(list);
        }
        return AjaxResult.error();
    }

    @GetMapping("/commonFeedback")
    public AjaxResult commonFeedback() {
        AppFeedBack feedBack = new AppFeedBack();
        feedBack.setIsCommon("1");
        List<AppFeedBack> list = feedBackService.selectAppFeedBackList(feedBack);
        return AjaxResult.success(list);
    }

    @PostMapping("/oneKeyRepair")
    public AjaxResult oneKeyRepair(@RequestBody AppOneKeyRepair appOneKeyRepair) {
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.selectWxUserById(id);
        if (wxUser != null) {
            appOneKeyRepair.setOpenId(wxUser.getOpenId());
            appOneKeyRepair.setNickName(wxUser.getNickName());
            appOneKeyRepair.setPhone(wxUser.getPhone());
            appOneKeyRepair.setCreateBy(wxUser.getNickName());
            appOneKeyRepair.setCreateTime(DateUtils.getNowDate());
            return toAjax(oneKeyRepairService.insertAppOneKeyRepair(appOneKeyRepair));
        }
        return AjaxResult.error("无用户信息");
    }

    @GetMapping("/deviceModel")
    public AjaxResult getDeviceModel(String modelCode) {
        AppDeviceModel appDeviceModel = appDeviceModelService.selectAppDeviceModelByModelCode(modelCode);
        if (appDeviceModel != null) {
            AppDeviceModelDto deviceModelDto = new AppDeviceModelDto();
            BeanUtil.copyProperties(appDeviceModel, deviceModelDto);
            AppDeviceDocument deviceDocument = new AppDeviceDocument();
            deviceDocument.setModelId(appDeviceModel.getModelId());
            List<AppDeviceDocument> files = appDeviceDocumentService.selectAppDeviceDocumentList(deviceDocument);
            List<AppDeviceDocument> fileList = new ArrayList<>();
            List<AppDeviceDocument> videoList = new ArrayList<>();
            for (AppDeviceDocument document : files) {
                if (document.getFileType() != null && document.getFileType().contains("mp4")) {
                    videoList.add(document);
                } else if (document.getFileType() != null && document.getFileType().contains("pdf")) {
                    fileList.add(document);
                }
            }
            deviceModelDto.setVideoList(videoList);
            deviceModelDto.setFileList(fileList);
            String type = deviceModelDto.getModelType();
            if (type != null) {
                String deviceType =  sysDictDataService.selectDictLabel("app_device_type", type);
                deviceModelDto.setModelType(deviceType);
            }
            return AjaxResult.success(deviceModelDto);
        }
        return AjaxResult.error("无设备型号信息");
    }

    @GetMapping("/document")
    public AjaxResult getDocument(Long documentId) {
        AppDeviceDocument appDeviceDocument = appDeviceDocumentService.selectAppDeviceDocumentByDocumentId(documentId);
        return AjaxResult.success(appDeviceDocument);
    }


    @GetMapping(value = "/getDangerousDeviceList")
    public AjaxResult getDangerousDeviceList() throws Exception {
        String token = DangerousToken.token;
        if (token == null) {
            token = DangerousToken.getToken();
        }
        if (token == null) {
            return AjaxResult.error("获取试剂柜Token失败");
        } else {
            com.alibaba.fastjson2.JSONObject jsonObject = getDangerousCabinetList(token);
            if (jsonObject != null) {
                Integer errCode = (Integer) jsonObject.get("errCode");
                if (errCode != null && errCode == 200) {
                    return AjaxResult.success(jsonObject);
                } else if (errCode != null && errCode == 401) {
                    token = DangerousToken.getToken();
                    if (token == null) {
                        return AjaxResult.error("获取试剂柜Token失败");
                    } else {
                        jsonObject = getDangerousCabinetList(token);
                        if (errCode != null && errCode == 200) {
                            return AjaxResult.success(jsonObject);
                        }
                    }
                }
                return AjaxResult.error("获取数据失败");
            } else {
                return AjaxResult.error("获取数据失败");
            }
        }
    }

    private com.alibaba.fastjson2.JSONObject getDangerousCabinetList(String token) throws Exception {
        String url = "https://dev.schemical.kakashine.com/openapi/cabinet/list";
        com.alibaba.fastjson2.JSONObject jsonObject = OkHttpUtil.getInstance().doGet(url, token);
        return jsonObject;
    }

    @GetMapping(value = "/getDangerousDeviceDetail/{code}")
    public AjaxResult getDetail(@PathVariable(value = "code") String code) throws Exception {
        String token = DangerousToken.token;
        if (token == null) {
            token = DangerousToken.getToken();
        }
        if (token == null) {
            return AjaxResult.error("获取试剂柜Token失败");
        } else {
            com.alibaba.fastjson2.JSONObject jsonObject = getDangerousCabinetDetail(token, code);
            if (jsonObject != null) {
                Integer errCode = (Integer) jsonObject.get("errCode");
                if (errCode != null && errCode == 200) {
                    return AjaxResult.success(jsonObject);
                } else if (errCode != null && errCode == 401) {
                    token = DangerousToken.getToken();
                    if (token == null) {
                        return AjaxResult.error("获取试剂柜Token失败");
                    } else {
                        jsonObject = getDangerousCabinetDetail(token, code);
                        errCode = (Integer) jsonObject.get("errCode");
                        if (errCode != null && errCode == 200) {
                            return AjaxResult.success(jsonObject);
                        }
                    }
                }
                return AjaxResult.error("获取数据失败");
            } else {
                return AjaxResult.error("获取数据失败");
            }
        }
    }

    private com.alibaba.fastjson2.JSONObject getDangerousCabinetDetail(String token, String code) throws Exception {
        String url = "https://dev.schemical.kakashine.com/openapi/cabinet/" + code;
        com.alibaba.fastjson2.JSONObject jsonObject = OkHttpUtil.getInstance().doGet(url, token);
        return jsonObject;
    }

    @GetMapping(value = "/getDangerousDeviceStoreDetail")
    public AjaxResult getStoreDetail(String cabinetId, String doorId) throws Exception {
        String token = DangerousToken.token;
        if (token == null) {
            token = DangerousToken.getToken();
        }
        if (token == null) {
            return AjaxResult.error("获取试剂柜Token失败");
        } else {
            com.alibaba.fastjson2.JSONObject jsonObject = getDangerousCabinetStoreDetail(token, cabinetId, doorId);
            if (jsonObject != null) {
                Integer errCode = (Integer) jsonObject.get("errCode");
                if (errCode != null && errCode == 200) {
                    return AjaxResult.success(jsonObject);
                } else if (errCode != null && errCode == 401) {
                    token = DangerousToken.getToken();
                    if (token == null) {
                        return AjaxResult.error("获取试剂柜Token失败");
                    } else {
                        jsonObject = getDangerousCabinetStoreDetail(token, cabinetId, doorId);
                        if (errCode != null && errCode == 200) {
                            return AjaxResult.success(jsonObject);
                        }
                    }
                }
                return AjaxResult.error("获取数据失败");
            } else {
                return AjaxResult.error("获取数据失败");
            }
        }
    }

    private com.alibaba.fastjson2.JSONObject getDangerousCabinetStoreDetail(String token, String cabinetId, String doorId) throws Exception {
        String url = "https://dev.schemical.kakashine.com/openapi/cabinet/inventory?cabinetId=" + cabinetId + "&doorId=" + doorId;
        com.alibaba.fastjson2.JSONObject jsonObject = OkHttpUtil.getInstance().doGet(url, token);
        return jsonObject;
    }
}
